package org.jeasy.rules.tutorials.helloworld;

import org.jeasy.rules.api.Facts;
import org.jeasy.rules.api.Rule;
import org.jeasy.rules.api.RuleListener;
import org.jeasy.rules.tutorials.exception.CustomException;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.UndeclaredThrowableException;

/**
 * @author yang_gsh
 */
public class HelloWorldRuleListener implements RuleListener {
    @Override
    public void onEvaluationError(Rule rule, Facts facts, Exception exception) {
        if (exception instanceof UndeclaredThrowableException) {
            Throwable undeclaredThrowable = ((UndeclaredThrowableException) exception).getUndeclaredThrowable();
            if (undeclaredThrowable instanceof InvocationTargetException) {
                throw (CustomException) ((InvocationTargetException) undeclaredThrowable).getTargetException();
            }
        }

        throw new CustomException(9999, exception.getMessage());
    }

    /**
     * Triggered after a rule has failed.
     *
     * @param rule      the current rule
     * @param facts     known facts after executing the rule
     * @param exception the exception thrown when attempting to execute the rule
     */
    @Override
    public void onFailure(Rule rule, Facts facts, Exception exception) {
        if (exception instanceof InvocationTargetException) {
            throw (CustomException) ((InvocationTargetException) exception).getTargetException();
        }


        throw new CustomException(9999, exception.getMessage());
    }
}
